import "./index.css";
import { bindActionCreators } from "redux";
import { useSelector, useDispatch } from "react-redux";
import { DailyWorkACs, State } from "../../../../state";
import { useState, BaseSyntheticEvent } from "react";
import { List, Typography, Divider, Button, Input, message } from "antd";

const DailyWork = () => {
  const [task, setTask] = useState("");
  const [isEditing, setIsEditing] = useState(false);
  const [placehoder, setPlacehoder] = useState("添加任务");
  const [curEditIndex, setCurEditIndex] = useState(-1);

  const dispatch = useDispatch();
  const dailyWorks = useSelector((state: State) => state.dailyWorks);
  const { addDailyTask, removeDailyTask, editDailyTask } = bindActionCreators(
    DailyWorkACs,
    dispatch
  );

  const changeTask = (e: BaseSyntheticEvent) => {
    setTask(e.target.value);
  };

  const addTask = () => {
    if (task) {
      addDailyTask(task);
      setTask("");
    } else {
      message.warning("不能添加空白任务！");
    }
  };

  const startEditTask = (index: number, item: string) => {
    setCurEditIndex(index);
    setIsEditing(true);
    setTask(item);
    setPlacehoder("编辑任务");
  };

  const cancelEidtTask = () => {
    setIsEditing(false);
    setCurEditIndex(-1);
    setTask("");
    setPlacehoder("添加任务");
  };

  const endEidtTask = () => {
    if (task) {
      editDailyTask(curEditIndex, task);
      cancelEidtTask();
    } else {
      message.warning("不能添加空白任务！");
    }
  };

  const removeTask = (index: number) => {
    removeDailyTask(index);
    cancelEidtTask();
  };

  const FootButton = () => {
    if (isEditing) {
      return (
        <>
          <Button className="edit-task-button" onClick={endEidtTask}>
            确定
          </Button>
          <Button className="edit-task-button" onClick={cancelEidtTask}>
            取消
          </Button>
        </>
      );
    } else {
      return (
        <Button className="add-task-button" onClick={addTask}>
          添加任务
        </Button>
      );
    }
  };

  return (
    <>
      <Divider orientation="left">任务列表</Divider>
      <List
        header={<div>每日任务</div>}
        footer={
          <>
            <Input
              value={task}
              onChange={changeTask}
              placeholder={placehoder}
            />
            <FootButton />
          </>
        }
        bordered
        dataSource={dailyWorks}
        renderItem={(item, index) => (
          <List.Item
            actions={[
              <Button type="text" onClick={() => startEditTask(index, item)}>
                编辑
              </Button>,
              <Button type="text" onClick={() => removeTask(index)}>
                删除
              </Button>,
            ]}
          >
            <Typography.Text mark>[ITEM]</Typography.Text> {item}
          </List.Item>
        )}
      />
    </>
  );
};

export { DailyWork };
